import { Transfer, Tree } from 'antd';
import React, { FC, useEffect, useState } from 'react';
import styles from './index.less';


// Customize Table Transfer
const isChecked = (selectedKeys, eventKey) => {
    return selectedKeys.indexOf(eventKey) !== -1;
};



const generateTree = (treeNodes = [], checkedKeys = []):any => {
    return treeNodes.map(({ children, ...props }) =>{
        let key = props.key+'';
        if (key.indexOf('_') && props.isLeaf) {
            key = key.split('_')[key.split('_').length-1]
        }
        return ({
            ...props,
            disabled: checkedKeys.includes(Number(key)),
            children: generateTree(children, checkedKeys),
        })
    });
};

const TreeTransfer = ({ dataSource, targetKeys, onLoadData, transferDataSource, ...restProps }) => {
    return (
        <div className={styles.tree}>
            <Transfer
                {...restProps}
                targetKeys={targetKeys}
                dataSource={transferDataSource}
                className="tree-transfer"
                render={item => item.title}
                showSelectAll={false}
                oneWay
            >
                {({ direction, onItemSelect, selectedKeys }) => {
                    if (direction === 'left') {
                        const checkedKeys = [...selectedKeys, ...targetKeys];
                        return (
                            <Tree
                                autoExpandParent={true}
                                defaultExpandAll={true}
                                blockNode
                                checkable
                                checkedKeys={checkedKeys}
                                treeData={generateTree(dataSource, targetKeys)}
                                onCheck={(_, { node: { key } }) => {
                                    onItemSelect(key, !isChecked(checkedKeys, key));
                                }}
                                onSelect={(selectKey, { node: { key } }) => {
                                    onLoadData(selectKey[0])
                                }}
                                
                            />
                        );
                    }
                }}
            </Transfer>
        </div>
    );
};

export default TreeTransfer;